const router = require('koa-router')()
const { deptScema } = require('../models/deptSchema')
const utlis = require('../utlis/common')
router.prefix('/dept')

//部门树形列表
router.get('/list', async ctx => {
    const { deptName } = ctx.request.query
    let params = {}
    if (deptName) params.deptName = deptName;
    let rootList = await deptScema.find(params)
   if(deptName){
    ctx.body=utlis.success(rootList)
   }else{
  let permissionList=  getTreeDept(rootList,null)
    ctx.body=utlis.success(permissionList)
   }
})

function getTreeDept(rootList,id,list=[]){
    for(let i=0;i<rootList.length;i++){
      let item = rootList[i]
      if(String(item.parentId.slice().pop()) == String(id)){
         list?.push(item._doc)
      }
    }
    list?.map(item=>{
        item['children'] = []
        getTreeDept(rootList,item._id,item.children)
        if(item.children.length == 0){
          delete item.children
        }
      })
    return list
 }

//部门：创建、编辑、删除
router.post('/operate', async ctx => {
    const { action, _id, ...params } = ctx.request.body
    let res, info
    try {
        if (action == 'create') {
             await deptScema.create(params)
            info = '创建成功'
        } else if (action == 'edit') {
            params.updateTime = new Date()
            res = await deptScema.findByIdAndUpdate(_id, params)
            info = '编辑成功'
        } else if (action == 'delete') {
            await deptScema.findByIdAndRemove(_id)
            await deptScema.deleteMany({ parentId: { $all: [_id] }})
            info='删除成功'
        }
      ctx.body=utlis.success('ok',info)
    } catch (error) {
     ctx.body=utlis.fail('操作失败')
    }
})


module.exports = router
